<!--
 * @description  : 证件-路径优化
 * @descriptionDetail: 证件-路径优化
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-09-13 10:29:13
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" title="路径优化">
    </theme-navbar>
    <!-- #endif -->

    <view class="content">
      <!-- 地图展示 -->
      <view class="map-content" :style="{width: getContainerWidth(), height: getContainerHeight()}" id="container"></view>
      <view class="map-btm-lay map-btm-lay-normal" v-show="showWin">
        <view class="map-btm-lay1">
          <text class="map-btm-lay1-title">
            {{ showItem.gfiName }}
          </text>
        </view>
        <text class="map-btm-item">
          发起人:{{ showItem.gfiSuname }}
        </text>
        <view class="u-m-y-10 map-btm-item">
          发起时间:{{ showItem.gfiStime }}
        </view>
        <view class="map-btm-item">
          当前阶段:{{ showItem.gfaName }}
        </view>
        <view style="display: flex; flex-direction: row;justify-content: space-between;" v-show="showItem.extData != -1">
          <u-button
            class="map-btm-btn"
            type="success"
            shape="circle"
            @click="ok"
          >
            查看详情
          </u-button>
          <u-button class="map-btm-btn" type="success" shape="circle" @click="naviBtn">
            导航
          </u-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  AMapMixin,
} from '@/common/AMapMixin.js';
import certificateService from "@/service/certificate/certificate.service.js";
export default {
  components: {},
  mixins: [AMapMixin,],
  data() {
    return {
      markers: [],
      currPosition: undefined,
      cPos: '', // 起点坐标
      cItem: '', // 距离中心最近的项
      cList: '', // 剩余检测项列表
      frequency:0, // 距离测量循环次数
      showWin:false, // 检查项信息窗口
      showItem:{}, // 当前点击检查项
      routeLines:[], // 路线
      finishedLists:[], // 已完成检查
      curIndex: -1,
      checkList: [],
    };
  },
  onLoad() {

  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.$modal.showLoading('地图加载中...');
    },
    initAmap() {
      let self = this;
      this.getCurrentLocation().then(
        res => {
          self.curPos = [res.lng, res.lat,];
          self.setMapInstance([res.lng, res.lat,]);
        },
        err => {
          self.justInitMap();
        }
      );
    },
    setMapInstance(cords) {
      if (!this.hasInited) return;
      let self = this;
      self.curCords = new AMap.LngLat(cords[0], cords[1]);
      self.amap = new AMap.Map('container', {
        center: self.curCords,
        showControlButton: true,
        resizeEnable: true, // 是否监控地图容器尺寸变化，默认值为false
        dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
        doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
        zoomEnable: true, // 地图是否可缩放，默认值为true
        rotateEnable: false, // 地图是否可旋转，3D视图默认为true，2D视图默认false
        zoom: 18,
      });
      self.setCurrentPointMarker();
      this.$modal.hideLoading();
      self.loadPlugin([
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.OverView',
        'AMap.MapType',
      ],
      function() {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        self.amap.addControl(new AMap.ToolBar());
        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        self.amap.addControl(new AMap.Scale());
        // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 10000, // 超过10秒后停止定位，默认：5s
          // buttonPosition:'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(5, 10), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          // zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
          content: '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
        });
        self.amap.addControl(geolocation);
      }
      );
      self.loadUI(['overlay/SimpleMarker','overlay/SimpleInfoWindow',],function(SimpleMarker,SimpleInfoWindow){
        AMap.SimpleMarker = SimpleMarker;
        AMap.SimpleInfoWindow = SimpleInfoWindow;
        self.initCheckItem();
      });
      // 地图缩放
      self.amap.on("zoomend", function() {
        // self.getNearRetailer();
      });
      // 地图移动
      self.amap.on("moveend", function() {
        // self.getNearRetailer();
      });
      self.cPos = `${self.curPos[0]},${self.curPos[1]}`;
      self.cList = self.checkList;
    },
    // 初始化检查任务项
    initCheckItem() {
      this.getDistance(this.cPos, this.cList);
    },
    // 距离测量
    getDistance(desNow, checkLists) {
      let self = this;
      let arr = checkLists.map(({
        latitude,
        longitude,
      }) => {
        return `${longitude},${latitude}`;
      })
      const SERVER_KEY = process.uniEnv.AMAP.SERVER_KEY;
      this.getCurDistance({
        destination: desNow,
		    key:SERVER_KEY, // 很重要，不能删，占位置
        origins: arr.join('|'),
        output: "JSON",
        type: 3,
      }).then((rs) => {
        self.frequency++;
        rs.sort((a, b) => {
          return a.distance - b.distance
        })
        let index = Number(rs[0].origin_id) - 1;
        self.cItem = checkLists.splice(index, 1);
        let cItemPos = `${self.cItem[0].longitude},${self.cItem[0].latitude}`
        let a = self.frequency;
        this.addMarker(self.cItem[0],self.frequency);
        self.drawRoute(self.cPos, cItemPos,self.frequency);
        // 调整视野达到最佳显示区域
        self.amap.setFitView([...self.markers,])
        self.cList = checkLists;
        self.cPos = `${self.cItem[0].longitude},${self.cItem[0].latitude}`
        if(self.cList.length > 0){
          self.getDistance(self.cPos, self.cList)
        }
      });
    },
    // 路线绘制
    drawRoute(originNow, desNow) {
      let startPoint = originNow.split(',');
      startPoint = [Number(startPoint[0]),Number(startPoint[1]),];
      let endPoint = desNow.split(',');
      endPoint = [Number(endPoint[0]),Number(endPoint[1]),];
      let self = this;
      self.getRoutsData({
        destination: desNow,
		key:"", // 很重要，不能删，占位置
        origin: originNow,
        output: "JSON",
      }).then((route) => {
        let paths = self.parseRouteToPath(route);
        // 将起点与终点加入线路中
        paths[0].unshift(startPoint);
        paths[paths.length - 1].push(endPoint);
        let routeLines = [];
        for (let i = 0; i < paths.length; i++) {
          let tmpPath = paths[i];
          let routeLine = new AMap.Polyline({
            path: tmpPath,
            isOutline: true,
            outlineColor: '#ffeeee',
            borderWeight: 2,
            strokeWeight: 5,
            strokeOpacity: 0.9,
            strokeColor: '#0091ff',
            lineJoin: 'round',
            showDir: true,
            zIndex: 10,
          });
          self.amap.add(routeLine);
          routeLines.push(routeLine);
        }
        self.routeLines.push(routeLines);
      })
    },
    parseRouteToPath(route) {
      let path = [];
      for (let i = 0, l = route.steps.length; i < l; i++) {
        let step = route.steps[i];
        let tmpPath = [];
        let tmpItems = step.polyline.split(';');
        for (let j = 0, n = tmpItems.length; j < n; j++) {
          let it = tmpItems[j].split(',');
          tmpPath.push([Number(it[0]), Number(it[1]),]);
        }
        path.push(tmpPath)
      }
      return path;
    },
    // 在地图上添加点
    addMarker(checkItem,i) {
      let self = this;
      this.$set(checkItem,'extData', i);
      let markPoint = {
        // 前景文字
        iconLabel: {
          innerHTML: i + '', // 设置文字内容
          style: {
            color: '#fff', // 设置文字颜色
          },
        },
        // 图标主题
        iconTheme: 'default',
        // 背景图标样式
        iconStyle: 'blue',
        map: self.amap,
        position: [checkItem.longitude, checkItem.latitude,],
        zIndex:40,
      }
      let point = new AMap.SimpleMarker(markPoint);
      point.setExtData(i);

      point.setMap(this.amap); // 在地图上添加点
      point.on('click',function(e){
        // openInfoWin();
        self.showWin = true;
        let index = e.target.getExtData();
        if(index == -1) {
          checkItem.extData = index;
          self.showItem = checkItem;
          return;
        }
        self.curIndex = index;
        self.resetPointStatus();
        self.updateLines(self.routeLines[self.curIndex - 1],'0');
        self.resetLinesStatus();
        self.showItem = checkItem;
      })
      self.markers.push(point);
    },
    // flag 0 表示 选中  1 表示正常  2 表示完成
    updateLines(ar, flag){
      for (let i = 0; i < ar.length; i++) {
        ar[i].setOptions({
          outlineColor: '#ffeeee',
          strokeColor:  flag == '2' ? "#A3A3A3" : (flag == 1 ? '#0091ff' : 'red'),
          borderWeight: 2,
          strokeWeight: 5,
          strokeOpacity: 0.9,
          zIndex: flag == '2' ? 25 : (flag == 1 ? 35 : 38),
        });
      }
    },
    // 恢复其他路线颜色
    resetLinesStatus(){
      for (let i = 0; i < this.routeLines.length; i++) {
        if(this.curIndex - 1 == i) continue;
        let index = this.markers[i].getExtData();
        if(index == -1){
          this.updateLines(this.routeLines[i],'2');
        }else{
          this.updateLines(this.routeLines[i],'1');
        }
      }
    },
    // 点击检查项时样式
    resetPointStatus(){
      for (let i = 0; i < this.markers.length; i++) {
        if(this.curIndex - 1 == i) {
          this.markers[i].setIconStyle('red');
        }else{
          let index = this.markers[i].getExtData();
          if(index == -1){
            this.markers[i].setIconStyle('lightgray');
          }else{
            this.markers[i].setIconStyle('blue');
          }
        }
      }
    },
    // 导航
    naviBtn(){

    },
    // 查看检查详情
    ok(){
      this.showWin = false;
      if(this.showItem.gfCode){
        let params = {
          curIndex:this.curIndex,
          docInsUuid:this.showItem.gfaiBizId,
          gfCode:this.showItem.gfCode,
        }
        this.setRouteParam(params);
        this.$u.route('pages/certificate/fieldAudit/entryFieldAudit');
      }else{
        this.$u.toast(`文书[${this.showItem.gfaName}]没有对应的路径`);
      }
    },
    updateBackState(params){
      let index = params.queryInfo.curIndex - 1;
      this.markers[index].setExtData(-1);
      this.markers[index].setIconStyle('lightgray');
      this.updateLines(this.routeLines[index],'2');
    },
    getContainerHeight() {
      return (this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight) + "px";
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + "px";
    },
    justInitMap() {
      this.$modal.alert("请在设备的设置中开启APP的定位权限后重新获取当前位置");
      this.amap = new AMap.Map('container', {
        showControlButton: true,
        zoom: 18,
      });
      this.$modal.hideLoading();
    },
  },
};
</script>
<style scoped lang="scss">
  @import "style/certificate/common.scss";

  uni-page-body {
    min-height: 100%;
    width: 100%;
    background-color: #F1F0F6;
  }

  #container {
    width: 100%;
    height: calc(100% - 88px);
  }
  .map-content{
    width: 100%;
    position: absolute;
    top: 0;
    z-index: 12;
  }
  .map-height{
    height: 100%;
  }
  .map-height-press{
    height: calc(100% - 380rpx);
  }
  .map-btm-lay-normal{
    height: 380rpx;
  }
  .map-btm-lay-me{
    height: 300rpx;
  }
  .map-btm-lay{
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 22;
    background-color: white;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    padding: 20rpx 60rpx;
    display: inline-flex;
    flex-direction: column;
  }
  .map-btm-btn{
    background-color: #2A79FF;
    width: 45%;
    margin: 40rpx 0 10rpx;
  }
  .map-btm-addr{
    font-size: 24rpx;
    color: #999;
    display: inline-flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  .map-btm-item{
    font-size: 24rpx;
    color: #999;
    display: inline-flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .map-btm-lay1{
    margin: 20rpx 0;
    display: inline-flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  .map-btm-lay1-title{
    flex-grow: 1;
    font-size: 30rpx;
    color: #555555;
  }
</style>
